import {Model} from './model';

export class ModelService {
  private modified: object[] = [];
  private added: object [] = [];
  private modifiedKeys: object = {};
  private addedKeys: object = {};

  constructor() {
  }

  collectAdded(data: Model) {
    this.addedKeys[data[data.getId()]] = data.rawData;
    this.added.push(data.rawData);
  }

  collectModified(data: object, preData: Model) {
    const key = data[preData.getId()];
    const oldModifiedData = this.modifiedKeys[key];
    const oldAddedData = this.addedKeys[key];

    if (oldAddedData) {
      // tslint:disable-next-line:forin
      for (const p in data) {
        oldAddedData[p] = data[p];
      }
    } else {
      if (oldModifiedData) {
        // tslint:disable-next-line:forin
        for (const p in data) {
          oldModifiedData[p] = data[p];
        }
      } else {
        this.modifiedKeys[key] = data;
        this.modified.push(data);
      }
    }
  }

  getModified() {
    return this.modified;
  }

  reset() {
    this.modified = [];
    this.added = [];
    this.modifiedKeys = {};
    this.addedKeys = {};
  }

  getAdded() {
    return this.added;
  }
}
